from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from .models import *
import hashlib
from django.views.decorators.cache import cache_page
from django.core.mail import send_mail, send_mass_mail


# Create your views here.

def login(request):
    """
    处理登陆请求
    :param request:
    :return:
    """
    print("_____login____执行")

    if request.method == "GET":
        return render(request, 'user/login.html', context={"h": 1})
    elif request.method == "POST":
        u_info = request.POST
        username = u_info.get("username")
        password = u_info.get("password")
        s_user = UserInfo.objects.filter(username=username)
        if not s_user:
            # 账号不存在的情况
            return render(request, 'user/login.html', context={"is_login": 1})
        if username != s_user[0].username or password != s_user[0].password:
            # 账号密码不匹配
            return render(request, 'user/login.html', context={"is_login": 1})
        # 登陆成功，将用户登陆成功的信息写入session
        request.session["user_id"] = s_user[0].id

        """
        subject  邮件主题
        message 邮件的文本内容
        from_email 发送者的邮箱地址，需要  'python<pydjango@163.com>'
        recipient_list  接收者的邮箱  
        fail_silently = False, 发送失败处理方式
        
        auth_user = 发送者的账号   EMAIL_HOST_USER
        auth_password = 客户端的授权密码  EMAIL_HOST_PASSWORD
        connection = None, 连接方式
        html_message = None ,html 文本格式的邮件内容
        
        """
        html_message = '<a href="https://www.taobao.com/">全场5折</a>'

        from userinfo import settings
        try:
            # send_mail("淘宝商城", "全场5折", settings.EMAIL_FROM, recipient_list=["pydjango@163.com", '371343545@qq.com'],
            #           html_message=html_message
            #           )

            msg1 = ("淘宝商城", html_message, settings.EMAIL_FROM, ["pydjango@163.com"])
            msg2 = ("淘宝商城", html_message, settings.EMAIL_FROM, ["371343545@qq.com"])

            send_mass_mail((msg1, msg2))

        except Exception as e:
            print(e)
        return redirect("/userinfo/")


# @cache_page(20)  # 缓存某个视图函数，参数是超时时间，单位是秒
def userinfo(request):
    """
    展示用户信息
    :param request:
    :return:
    """
    user_id = request.session.get("user_id")  # 从session 里面获取user_id 如果有表示已经登录，

    if not user_id:
        # session 里面没有找到对应会话的id说明没有登陆，重定向到登录页面
        return redirect('/login/')
    # 登陆成功
    user = UserInfo.objects.get(id=user_id)
    return render(request, 'user/userinfo.html', context={"user": user})


def register(request):
    if request.method == "GET":
        return render(request, 'user/register.html')
    elif request.method == "POST":
        u_info = request.POST
        print(u_info)
        username = u_info.get("username")
        nickname = u_info.get("nickname")
        password = u_info.get("password")
        gender = u_info.get("gender")
        sign = u_info.get("sign")
        pic_ = request.FILES.get('pic')

        # has = hashlib.md5()
        # has.update(password.encode("utf-8"))
        # password = has.hexdigest()  # md5加密

        try:
            # 将数据写入数据库
            user = UserInfo.objects.create(username, password, nickname, gender, sign, pic_)
            user.save()
        except Exception as e:
            # 没有保存成功返回到注册页面
            # return render(request, 'user/register.html')
            return JsonResponse({"success": 1, "msg": "注册失败"})

        else:
            # 登陆成功重定向到登陆页面
            return JsonResponse({"success": 0, "msg": "注册成功", 'url': '/login/'})


def logout(request):
    del request.session["user_id"]
    return HttpResponse('退出登录成功')


def check_username(request):
    """
    校验账号是否可以注册
    :param request:
    :return:
    """
    name = request.POST.get("username")

    user_info = UserInfo.objects.filter(username=name)
    if not name:
        return JsonResponse({"success": 1, 'msg': "账号不能为空"})
    if user_info:
        return JsonResponse({"success": 1, 'msg': "账号已存在"})
    return JsonResponse({"success": 0, 'msg': "账号可以注册"})
